package sunhang3.parse;

import java.util.ArrayList;
import java.util.List;

public class NaluMgr {
    private byte[] buffer = new byte[0];

    public List<byte[]> append(byte[] fromTcp, int len) {
        byte[] newBuffer = new byte[buffer.length + len];
        System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
        System.arraycopy(fromTcp, 0, newBuffer, buffer.length, len);
        buffer = newBuffer;

        List<byte[]> list = new ArrayList<>();
        int index = 0;
        int next;

        while ((next = Utils.findNextFrame(buffer, index + 2, buffer.length)) != -1) {
            byte[] bytes = new byte[next - index];
            System.arraycopy(buffer, index, bytes, 0, bytes.length);
            list.add(bytes);
            index = next;
        }

        if (index != 0) {
            byte[] bytes = new byte[buffer.length - index];
            System.arraycopy(buffer, index, bytes, 0, bytes.length);
            buffer = bytes;
        }

        return list;
    }
}
